package com.github.wxiaoqi.security.biz.modules.comment.biz;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.wxiaoqi.security.auth.common.util.SnowFlake;
import com.github.wxiaoqi.security.biz.modules.activity.entity.ActivityInfo;
import com.github.wxiaoqi.security.biz.modules.activity.mapper.ActivityInfoMapper;
import com.github.wxiaoqi.security.biz.modules.comment.entity.Comment;
import com.github.wxiaoqi.security.biz.modules.comment.mapper.CommentMapper;
import com.github.wxiaoqi.security.biz.modules.community.entity.CommunityViewpoint;
import com.github.wxiaoqi.security.biz.modules.community.mapper.CommunityViewpointMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.cms.request.CmsQueryCommentParam;
import com.github.wxiaoqi.security.common.cms.request.CmsSaveCommentParam;
import com.github.wxiaoqi.security.common.enums.CommentModuleNo;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.util.PageUtils;
import com.github.wxiaoqi.security.common.util.ResponseHelper;

import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * 
 *
 * @author chj
 * @email 
 * @date 2018-07-09 14:10:44
 */
@Slf4j
@Service
public class CommentBiz extends BaseBiz<CommentMapper,Comment> {
	
	@Autowired
	private CommunityViewpointMapper viewPointMapper;
	
	@Autowired
	private ActivityInfoMapper activityInfoMapper;
	
	/**
	 * 查询观点评论 
	 */
	@ResponseBody
	@RequestMapping(value="/query", method = RequestMethod.POST)
	public Map<String, Object> queryComment(CmsQueryCommentParam param) {

		log.info("请求查询话题---start---{}",param);
		Integer currentPage = param.getPage();//当前页
		Integer pageSize = param.getLimit();//条数
		String id = param.getId();//话题编号
		String commentModuleNo = param.getCommentModuleNo();//评论模块编号
		Map<String, Object> queryMap = new HashMap<>();
		queryMap.put("commentTargetId", id);
		queryMap.put("commentModuleNo", commentModuleNo);
		Comment comment1 = new Comment();
		comment1.setCommentTargetId(id);
		comment1.setCommentModuleNo(commentModuleNo);
		Integer total = mapper.selectCount(comment1);
		int pageSizeInt = Integer.valueOf(pageSize);
		PageUtils pageUtil = new PageUtils(total, pageSizeInt, Integer.valueOf(currentPage));
		param.setTotalCount(total);
		log.info("请求查询话题--pageUtil---{}",pageUtil.toString());
		if (isLastPage(param)) {
			return ResponseHelper.success(null,pageUtil, "01", "已经到最后一条了~");
		}
		List<Comment> list = mapper.select(comment1);
		log.info("请求查询话题--list---{}",list.toString());
		String format = "yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(format);  
		for (Object object : list) {
			Comment comment = (Comment) object;
			String time = sdf.format(comment.getCommentTime());
			try {
				comment.setCommentTime(sdf.parse(time));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		
		return ResponseHelper.success(list,pageUtil, "00", "查询成功");
	
	}
	
	/**
	 * 查询观点评论 
	 * 查询多级评论
	 */
	@ResponseBody
	@RequestMapping(value="/queryMany", method = RequestMethod.POST)
	public Map<String, Object> queryTwo(CmsQueryCommentParam param) {
		log.info("查询观点评论 ---start---{}",param);
		String commentTargetId = param.getCommentTargetId();//观点编号
		Map<String, Object> queryMap = new HashMap<>();
		String commentModuleNo = param.getCommentModuleNo();//评论模块编号
		queryMap.put("commentModuleNo", commentModuleNo);
		queryMap.put("commentTargetId", commentTargetId);
		queryMap.put("commentType", "1");
		Comment comment1 = new Comment();
		comment1.setCommentTargetId(commentTargetId);
		comment1.setCommentModuleNo(commentModuleNo);
		comment1.setCommentType("1");
		List<Comment> commentList = mapper.select(comment1);
		List<Map<String, Object>> resultMaps = new ArrayList<>();
		String format = "yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(format);  
		Map<String, Object> resultMap;
		for (Comment comment : commentList) {
			try {
				String time = sdf.format(comment.getCommentTime());
				comment.setCommentTime(sdf.parse(time));
				resultMap = new HashMap<>();
				Map<String, Object> subQueryMap = new HashMap<>();
				subQueryMap.put("commentModuleNo", commentModuleNo);
				subQueryMap.put("commentTargetId", commentTargetId);
				subQueryMap.put("commentType", 2);//查询类型为回复的
				subQueryMap.put("parentId", comment.getId());//查询类型为回复的
				resultMaps.add(resultMap);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return ResponseHelper.success(resultMaps,null, "00", "查询成功");
	}
	
	/**
	 * 评论回复添加
	 */
	@ResponseBody
	@RequestMapping(value="/add", method = RequestMethod.POST)
	public Map<String, Object> addPointComment(CmsSaveCommentParam param) {
		log.info("评论回复添加 ---start---{}",param);
		String commentType = param.getCommentType();//1评论2回复
		String customerId = param.getCustomerId();
		String commentModuleNo = param.getCommentModuleNo();
		String commentByName = param.getCommentByName();
		
		String commentContent = param.getCommentContent();
		String commentTargetId = param.getCommentTargetId();
		String merchantId = param.getMerchantId();
		String platformId = param.getPlatformId();
		String commentTargetUserName = param.getCommentTargetUserName();
		String commentTargetUserId = param.getCommentTargetUserId();
		try {
			//如果是观点更新评论量
			if(CommentModuleNo.home_viewpoint.getCode().equals(commentModuleNo)){
				CommunityViewpoint point = viewPointMapper.selectByPrimaryKey(commentTargetId);
				if(point == null){
					return ResponseHelper.success(null,null, "01", "未查询到观点记录");
				}
				Integer commenCount = point.getCommentCount();
				commenCount = commenCount + 1;
				point.setCommentCount(commenCount);
				viewPointMapper.updateByPrimaryKey(point);
			}else if (CommentModuleNo.activity_activity.getCode().equals(commentModuleNo)) {
				ActivityInfo activityInfo = activityInfoMapper.selectByPrimaryKey(commentTargetId);
				if(activityInfo == null){
					return ResponseHelper.success(null,null, "01", "活动不存在");
				}
				Integer commenCount = activityInfo.getCommentCount();
				commenCount = commenCount + 1;
				activityInfo.setCommentCount(commenCount);
				activityInfoMapper.updateByPrimaryKey(activityInfo);
			}
			Comment comment = new Comment();
			String idString = String.valueOf(SnowFlake.getId());
			comment.setId(idString);
			comment.setCommentByName(commentByName);
			comment.setCommentContent(commentContent);
			comment.setCommentTargetId(commentTargetId);
			comment.setCommentType(commentType);
			comment.setCommentByName(commentByName);
			comment.setCustomerId(customerId);
			comment.setCommentModuleNo(commentModuleNo);
			comment.setMerchantId(merchantId);
			comment.setPlatformId(platformId);
			comment.setCommentTime(new Date());
			comment.setCommentTargetUserId(commentTargetUserId);
			comment.setCommentTargetUserName(commentTargetUserName);
			comment.setAvatarUrl(param.getAvatarUrl());
			if ("02".equals(commentModuleNo)) {
				//卖朋友多级评论
				comment.setParentId(param.getParentId());
			}
			mapper.insert(comment);
			log.info("添加观点评论。。。。。end。。");
			return ResponseHelper.success(null,null, "00", "评论成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseHelper.success(null,null, "01", "评论异常");
	}
	
	/**
	 * 后台查询评论列表
	 * @param param
	 * @return
	 */
	public TableResultResponse<Comment> queryComments(CmsQueryCommentParam param) {
		log.info("查询评论列表。。。{}"+param);
			Example example = new Example(Comment.class);
			Criteria criteria = example.createCriteria();
			if (param.getPlatformId() != null && param.getPlatformId().length() > 0) {
				criteria.andEqualTo("platformId",param.getPlatformId());
			}
			if (param.getMerchantId() != null && param.getMerchantId().length() > 0) {
				criteria.andEqualTo("merchantId",param.getMerchantId());
			}
			if (param.getCommentModuleNo() != null && param.getCommentModuleNo().length() > 0) {
				criteria.andEqualTo("commentModuleNo",param.getCommentModuleNo());
			}
			example.setOrderByClause("comment_time desc");
			Page<Comment> result = PageHelper.startPage(param.getPage(), param.getLimit());
			List<Comment> list = mapper.selectByExample(example);
			TableResultResponse<Comment> table = new TableResultResponse<>(result.getTotal(), list);
		return table;
	}
	
	/**
	 * 删除评论
	 * @param param
	 * @return
	 */
	public Map<String, Object> deleteComment(CmsQueryCommentParam param) {
		log.info("删除评论。。。{}"+param);
		Map<String, Object> respMap = new HashMap<>();
		try {
			String id = param.getId();
			Comment comment = mapper.selectByPrimaryKey(id);
			if (comment != null) {
				mapper.delete(comment);
				respMap.put("code", "00");
				respMap.put("msg", "删除成功");
			}else {
				respMap.put("code", "01");
				respMap.put("msg", "评论不存在");
			}
		} catch (Exception e) {
			respMap.put("code", "01");
			respMap.put("msg", "操作异常");
		}
		return respMap;
	}
	
	protected boolean isLastPage(CmsQueryCommentParam param) {
		
		Integer currentPage = param.getPage();//当前页
		PageUtils pageUtil = new PageUtils(Integer.valueOf(param.getTotalCount()), 10, currentPage);
		Integer nextPage = Integer.valueOf(currentPage) + 1;
		boolean flag =  false;
		if(nextPage > pageUtil.getTotalPage()){
			//下一页超出总页数
			flag =  true;
		}
		return flag;
	}
}